package cn.whitecao.contentcenter.config;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;

/**
 * @author ：腼腆的老黄.
 * @date ：Created in 2019-08-14 11:11
 */
@Slf4j
//@RequiredArgsConstructor
public class NacosWeightedRule extends AbstractLoadBalancerRule {
    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        //
        try {
            BaseLoadBalancer loadBalancer= (BaseLoadBalancer) this.getLoadBalancer();
            //获取想要请求的微服务名称
            String name = loadBalancer.getName();
            //拿到微服务相关的api
                NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
            //nacos client  自动通过基于权重的算法 来进行选择实例
            Instance instance = namingService.selectOneHealthyInstance(name);
            log.info("nacos权重 选择的实例是: port={} , weight={} , instance={}",instance.getPort(),instance.getWeight(),instance);
            return new NacosServer(instance);
        } catch (NacosException e) {
            log.info("nacos权重异常:{}",e.getMessage());
            return null;
        }
    }
}
